<?php
	$saveFolder = 'image_cache'. '/' . date("Y") . '/' . date("m") .'/';
	if (!is_dir('image_cache')){
		mkdir('image_cache');
	}
	if (!is_dir('image_cache'.'/'.date('Y'))){
		mkdir('image_cache'.'/'.date('Y'));
	}
	if (!is_dir($saveFolder)){
		mkdir($saveFolder);
	}
	if (!empty($_FILES) && $_REQUEST["active_file"]) {
		$file_key = $_REQUEST["active_file"];
		$file = $_FILES[$file_key];

		$exten = strtolower(array_pop(explode('.',$file['name'])));
		$newfileName = strtolower(md5(uniqid(mt_rand(), true)));
		$targetFileName = $newfileName . '.' .$exten; 
		// Validate the file type
		$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
		$fileParts = pathinfo($file['name']);
		if (in_array($exten,$fileTypes)) {
			$tmpName = $saveFolder.$targetFileName;
			move_uploaded_file($file['tmp_name'], $tmpName);
			echo "{ \"result\":\"success\", \"url\":\"{$tmpName}\"}";
		} else {
			echo  "{ \"result\":\"Invalid file type.\", \"url\":\"\"}";
		}
	}
?>